package com.yupi.mianshiya.aop;
import com.jd.platform.hotkey.client.callback.JdHotKeyStore;
import com.yupi.mianshiya.annotation.HotKeyCache;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;

import java.util.Arrays;

@Aspect
@Component
public class HotKeyCacheAspect {
    // 假设 JdHotKeyStore 是热 key 探测和本地缓存的工具类

//    private final JdHotKeyStore jdHotKeyStore = null;
//
//    public HotKeyCacheAspect(JdHotKeyStore jdHotKeyStore) {
//        this.jdHotKeyStore = jdHotKeyStore;
//    }

    @Around("@annotation(hotKeyCache)")
    public Object cacheHotKey(ProceedingJoinPoint joinPoint, HotKeyCache hotKeyCache) throws Throwable {
        // 生成缓存 key
        String key = generateKey(hotKeyCache.key(), joinPoint);

        // 检查是否是热 key
        if (JdHotKeyStore.isHotKey(key)) {
            // 尝试从本地缓存获取
            Object cachedValue = JdHotKeyStore.get(key);
            if (cachedValue != null) {
                return cachedValue;
            }
        }

        // 执行目标方法
        Object result = joinPoint.proceed();

        // 如果是热 key，设置本地缓存
//        if (JdHotKeyStore.isHotKey(key)) {
            JdHotKeyStore.smartSet(key, result);
//        }

        return result;
    }

    private String generateKey(String keyExpression, ProceedingJoinPoint joinPoint) {
        // 根据 keyExpression 和方法参数生成最终的缓存 key
        // 这里可以实现更复杂的 key 生成逻辑
        return keyExpression + "_" + Arrays.toString(joinPoint.getArgs());
    }
}
